package com.rangers.manage.email.config;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import com.rangers.manage.email.domain.EmailConstant;
import com.rangers.manage.email.handler.EmailSendTask;
import com.rangers.manage.email.handler.EmailServerProvider;

/**
 * 邮件管理系统配置
 * 
 * @author fuhw
 * @date 2017年10月25日
 */
@Component
public class EmailManageConfig {

	@Configuration
	@EnableConfigurationProperties(EmailServerProperty.class)
	protected static class EmailPropertyConfig {
		@Bean
		public EmailServerProvider merchantProvider(EmailServerProperty emailProperty) {
			return new EmailServerProvider(emailProperty);
		}
	}

	/**
	 * velocity模版引擎
	 */
	@Bean
	public VelocityEngine velocityEngine() {
		VelocityEngine engine = new VelocityEngine();
		engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
		engine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
		engine.init();
		return engine;
	}

	@Bean
	public ClassLoaderTemplateResolver emailTemplateResolver() {
		ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
		resolver.setTemplateMode("HTML5");
		resolver.setCharacterEncoding("UTF-8");
		return resolver;
	}

	@Bean
	public SpringTemplateEngine springTemplateEngine() {
		SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
		// 将加载模版类注册到springTemplateEngine中，在加载Thymeleaf时使用
		springTemplateEngine.addTemplateResolver(emailTemplateResolver());
		return springTemplateEngine;
	}

	@Bean
	public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		threadPoolTaskExecutor.setCorePoolSize(EmailConstant.CORE_POOL_SIZE);
		threadPoolTaskExecutor.setMaxPoolSize(EmailConstant.MAX_POOL_SIZE);
		threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(Boolean.TRUE);
		threadPoolTaskExecutor.setKeepAliveSeconds(EmailConstant.KEEP_ALIVE_SECONDS);
		return threadPoolTaskExecutor;
	}

	@Bean
	CommandLineRunner runEmailSendTask( EmailSendTask emailSendTask) {
		return (args) -> {
			emailSendTask.doSendTask();
		};
	}
}
